package cn.jh.clearing.service;

import cn.jh.clearing.business.CoinRecordBusiness;
import cn.jh.clearing.business.PaymentOrderBusiness;
import cn.jh.clearing.business.ProfitRecordBusiness;
import cn.jh.clearing.pojo.*;
import cn.jh.clearing.util.RestTemplateUtil;
import cn.jh.clearing.util.Util;
import cn.jh.common.utils.*;
import io.jsonwebtoken.lang.Strings;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.jh.common.utils.CommonConstants.*;


@Controller
public class PaymentService {

    private static final Logger LOG = LoggerFactory.getLogger(PaymentService.class);

    private final PaymentOrderBusiness paymentOrderBusiness;
    private final ProfitRecordBusiness profitRecordBusiness;
    private final CoinRecordBusiness coinRecordBusiness;
    private final Util util;
    private final RestTemplateUtil restTemplateUtil;

    @Autowired
    public PaymentService(PaymentOrderBusiness paymentOrderBusiness, ProfitRecordBusiness profitRecordBusiness,
                          CoinRecordBusiness coinRecordBusiness, Util util, RestTemplateUtil restTemplateUtil) {
        this.paymentOrderBusiness = paymentOrderBusiness;
        this.profitRecordBusiness = profitRecordBusiness;
        this.coinRecordBusiness = coinRecordBusiness;
        this.util = util;
        this.restTemplateUtil = restTemplateUtil;
    }

    /**
     * 获取指定用户的交易明细
     *
     * @param token 登录token
     * @param queryCriteria 查询条件封装
     * @param page 当前页
     * @param size 分页大小
     * @param direction 升序/降序
     * @param sortProperty 排序字段
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/{token}")
    public @ResponseBody
    Object findPaymentOrder(@PathVariable("token") String token,
                            PaymentQueryCriteria queryCriteria,
                            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
                            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
                            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
                            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN, "token无效");
        }
        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
        queryCriteria.setUser_id(userId);
        String type = queryCriteria.getType();
        try {
            if (ORDER_TYPE_WITHDRAW.equals(type)) {
                //提现
                Object objectRes = paymentOrderBusiness.getWithDrawPage(queryCriteria.getStatus(), userId, page, size);
                return CommonsUtil.returnSuccess("提现记录查询成功！", objectRes);
            }
            if (ORDER_TYPE_REBATE.equals(type)) {
                //分润
                Object objectRes = paymentOrderBusiness.getRebatePage(token, page, size);
                LOG.debug("查询分润记录结果objectRes = " + objectRes);
                return CommonsUtil.returnSuccess("分润记录查询成功！", objectRes);
            }
            if (ORDER_TYPE_TOPUP.equals(type)) {
                //充值
                Object objectRes = paymentOrderBusiness.getRechargePage(queryCriteria.getStatus(), userId, page, size);
                LOG.debug("查询充值记录结果objectRes = " + objectRes);
                return CommonsUtil.returnSuccess("充值记录查询成功！", objectRes);
            }
            if (ORDER_TYPE_PAY.equals(type)) {
                //支付
                Object objectRes = paymentOrderBusiness.getPayPage(queryCriteria.getStatus(), userId, page, size);
                LOG.debug("查询支付记录结果objectRes = " + objectRes);
                return CommonsUtil.returnSuccess("支付记录查询成功！", objectRes);
            }
        } catch (Exception e) {
            if (e.getMessage().contains("查询失败")) {
                return CommonsUtil.returnError(e.getMessage());
            }
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
        Page<PaymentOrder> pageResult = paymentOrderBusiness.findPaymentOrder(queryCriteria, pageable);
        return CommonsUtil.returnOK(pageResult);
    }

    /**
     * 更新第三方的订单号
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update/thirdordercode")
    public @ResponseBody
    Object updatePaymentThirdOrdercde(HttpServletRequest request,
                                      @RequestParam(value = "order_code") String orderCode,
                                      @RequestParam(value = "third_code") String thirdcode) {
        paymentOrderBusiness.updateThirdcodeByOrdercode(thirdcode, orderCode);
        return CommonsUtil.returnOK();
    }

    /**
     * 更新第三方的订单号
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update/autoclearing")
    public @ResponseBody
    Object updateAutoClearing(HttpServletRequest request,
                              @RequestParam(value = "order_code") String orderCode,
                              @RequestParam(value = "auto_clearing") String autoclearing) {
        paymentOrderBusiness.updateAutoClearingByOrdercode(orderCode, autoclearing);
        return CommonsUtil.returnOK();
    }

    /* 根据订单号获取订单对象 */

    /**
     * 获取用户的交易明喜
     **/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/orderidandcode")
    public @ResponseBody
    Object queryPaymentOrderById(
            @RequestParam(value = "orderId") Integer orderId,
            @RequestParam(value = "orderCode") String orderCode) {
        PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderByIdAndCode(orderId, orderCode);
        if (paymentOrder == null) {
            return CommonsUtil.returnError(CommonConstants.ERROR_PAYMENT_NOT_EXIST, "失败");
        }
        return CommonsUtil.returnOK(paymentOrder);
    }

    /**
     * 获取用户的交易明喜
     **/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/ordercode")
    public @ResponseBody
    Object queryPaymentOrder(@RequestParam(value = "order_code") String orderCode) {
        PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);
        if (paymentOrder == null) {
            return CommonsUtil.returnError(CommonConstants.ERROR_PAYMENT_NOT_EXIST, "失败");
        }
        return CommonsUtil.returnOK(paymentOrder);
    }

    /**
     * 获取用户的交易明喜
     **/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/thirdcode")
    public @ResponseBody
    Object queryPaymentOrderByThirdcode(@RequestParam(value = "third_code") String thirdcode) {
        PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderByThirdcode(thirdcode);
        if (paymentOrder == null) {
            return CommonsUtil.returnError(CommonConstants.ERROR_PAYMENT_NOT_EXIST, "失败");
        }
        return CommonsUtil.returnOK(paymentOrder);
    }

    /**
     * 根据外放的订单号， 获取订单
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/outordercode")
    public @ResponseBody
    Object queryPaymentOrderByOutOrdercode(HttpServletRequest request,
                                           @RequestParam(value = "order_code") String orderCode) {
        PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOderByOutOrdercode(orderCode);
        if (paymentOrder == null) {
            return CommonsUtil.returnError(CommonConstants.ERROR_PAYMENT_NOT_EXIST, "失败");
        }
        return CommonsUtil.returnOK(paymentOrder);
    }

    // 根据多个条件查询订单信息
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/all")
    public @ResponseBody
    Object pageAllPaymentQuery(HttpServletRequest request,
                               @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                               // 订单号
                               @RequestParam(value = "order_code", required = false) String order_code,
                               // 外放订单号
                               @RequestParam(value = "out_order_code", required = false) String outorderCode,
                               // 用户编号
                               @RequestParam(value = "userid", defaultValue = "0", required = false) long userid,
                               // 贴牌id
                               @RequestParam(value = "brand_id", defaultValue = "-1", required = false) long brand_id,

                               // 等级
                               @RequestParam(value = "grade", required = false) String grade,

                               // 身份证号
                               @RequestParam(value = "idcard", required = false) String idcard,

                               // 银行卡号
                               @RequestParam(value = "cardNo", required = false) String cardNo,

                               /// **0 充值 1支付 2提现 3退款 */
                               @RequestParam(value = "type", required = false) String order_type,

                               /** 0 待完成 1已成功已结算 2已取消 3待处理 4已成功待结算 */
                               @RequestParam(value = "status", defaultValue = "", required = false) String order_status,

                               @RequestParam(value = "start_time", required = false) String startTime,
                               @RequestParam(value = "end_time", required = false) String endTime,
                               @RequestParam(value = "page", defaultValue = "0", required = false) int page,
                               @RequestParam(value = "size", defaultValue = "20", required = false) int size,
                               @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
                               @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        Date StartTimeDate = null;
        try {
            if (startTime != null && !startTime.trim().equalsIgnoreCase("")) {
                StartTimeDate = DateUtil.getDateFromStr(startTime);
            }
        } catch (Exception e1) {
            LOG.error("startTime转换异常===========================" + e1);
            startTime = null;
        }
        Date endTimeDate = null;

        try {
            if (endTime != null && !endTime.trim().equalsIgnoreCase("")) {
                endTimeDate = DateUtil.getDateFromStr(endTime);
            }
        } catch (Exception e) {
            LOG.error("endTime转换异常============================" + e);
            endTime = null;
        }

        List<PaymentOrder> PaymentOrders = new ArrayList<PaymentOrder>();

        Map<String, Object> map = new HashMap<String, Object>();

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

        // 根据多个条件查询订单信息
        Map queryPaymentOrderAll = paymentOrderBusiness.queryPaymentOrderAll(startTime, endTime, phone, order_code,
                order_type, order_status, brand_id, pageable);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, queryPaymentOrderAll);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        String userId = "";
        if (phone != null && !phone.equals("")) {
            URI uri = util.getServiceUrl("user", "error url request!");
            String url = uri.toString() + "/v1.0/user/query/phone";
            /* 根据的用户手机号码查询用户的基本信息 */
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("phone", phone);
            requestEntity.add("brandId", brand_id + "");
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================" + result);
            JSONObject jsonObject = JSONObject.fromObject(result);
            JSONObject resultObj = jsonObject.getJSONObject("result");

            if (resultObj.containsKey("id")) {
                userId = resultObj.getString("id");
            } else {
                userId = "0";
            }
        }

        /*
         * 身份证不为空判定
         **/
        if (idcard != null && !idcard.equals("")) {

            /* 获取身份证实名信息 */
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/paymentchannel/realname/idcard";

            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("idcard", idcard);
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.fromObject(result);
            if (result == null) {
                userId = "0";
            } else {
                userId = jsonObject.getString("userId");
            }
        }
        /*
         * 银行卡不为空判定
         **/
        if (idcard != null && !idcard.equals("")) {

            /* 获取银行卡信息 */
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/user/bank/default/cardno";
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("cardno", cardNo);
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.fromObject(result);
            if (result == null) {
                userId = "0";
            } else {
                userId = jsonObject.getString("userId");
            }

        }

        return map;
    }

    /* 创建或更新支付/充值/订单 */

    /**
     * 如果选择三级分销产品升级， 那么product_id需要填入三级分销的产品 id realamount手机充值用
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/add")
    public @ResponseBody
    Object addPaymentOrder(HttpServletRequest request,
                           @RequestParam(value = "type", defaultValue = "0", required = false) String type,
                           @RequestParam(value = "desc", defaultValue = "", required = false) String desc,
                           @RequestParam(value = "desc_code", defaultValue = "", required = false) String descCode,
                           @RequestParam(value = "notify_url", defaultValue = "", required = false) String notifyUrl,
                           @RequestParam(value = "return_url", defaultValue = "", required = false) String returnUrl,
                           @RequestParam(value = "out_order_code", defaultValue = "", required = false) String outOrderCode,
                           @RequestParam(value = "phone") String phone,
                           @RequestParam(value = "openid", required = false) String openid,
                           @RequestParam(value = "orderCode", required = false) String orderCode,
                           @RequestParam(value = "brand_id", required = false, defaultValue = "-1") String brand_id,
                           @RequestParam(value = "amount") String amount,
                           // 车牌号
                           @RequestParam(value = "carNo", required = false) String carNo,
                           // 手机充值用的真实
                           @RequestParam(value = "realamount", required = false) String realamount,
                           // 充值手机号
                           @RequestParam(value = "phonebill", required = false) String phonebill,
                           @RequestParam(value = "remark", defaultValue = "", required = false) String remark,
                           @RequestParam(value = "channel_tag") String channeltag,
                           @RequestParam(value = "bank_card", required = false) String bankcard,
                           @RequestParam(value = "product_id", required = false) String prodid) {
        Map<String, Object> map = new HashMap<String, Object>();
        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonObject;
        JSONObject resultObj;
        PaymentOrder paymentOrder = new PaymentOrder();


        paymentOrder.setChannelid(0);
        paymentOrder.setChannelname(null);
        paymentOrder.setChannelTag(channeltag);
        paymentOrder.setOpenid(openid);
        paymentOrder.setBankcard(bankcard);

        paymentOrder.setAmount(new BigDecimal(amount));
        if (remark == null) {
            paymentOrder.setRemark("");
        } else {
            paymentOrder.setRemark(remark);
        }
        paymentOrder.setCreateTime(new Date());
        paymentOrder.setUpdateTime(new Date());
        paymentOrder.setDesc(desc);
        paymentOrder.setDescCode(descCode);
        paymentOrder.setPhone(phone);
        paymentOrder.setOutMerOrdercode(outOrderCode);
        paymentOrder.setType(type);
        paymentOrder.setOutNotifyUrl(notifyUrl);
        paymentOrder.setOutReturnUrl(returnUrl);
        paymentOrder.setStatus(CommonConstants.ORDER_READY);

        if (prodid != null && !prodid.equalsIgnoreCase("")) {
            paymentOrder.setThirdlevelid(prodid);
        }
        LOG.info("RESULT================" + paymentOrder.getOrdercode() + "************************************");
        paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
        LOG.info("RESULT================" + paymentOrder.toString() + "************************************");
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        map.put(CommonConstants.RESULT, paymentOrder);
        return map;

    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/add2")
    public @ResponseBody
    Object addPaymentOrderFirst(HttpServletRequest request,
                                @RequestParam(value = "type", defaultValue = "0", required = false) String type,
                                @RequestParam(value = "desc", defaultValue = "", required = false) String desc,
                                @RequestParam(value = "userId", defaultValue = "", required = false) long userId,
                                @RequestParam(value = "bankCard", defaultValue = "", required = false) String bankCard,
                                @RequestParam(value = "amount", defaultValue = "", required = false) String amount,
                                @RequestParam(value = "orderCode", defaultValue = "", required = false) String orderCode,
                                @RequestParam(value = "channel_tag", defaultValue = "", required = false) String channelTag) {
        PaymentOrder paymentOrder = new PaymentOrder();
        paymentOrder.setAmount(new BigDecimal(amount));
        paymentOrder.setType("9");
        paymentOrder.setDesc(desc);
        paymentOrder.setOrdercode(orderCode);
        paymentOrder.setChannelTag(channelTag);
        paymentOrder.setUserid(userId);
        paymentOrder.setBankcard(bankCard);
        paymentOrder.setCreateTime(new Date());
        paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
        return CommonsUtil.returnSuccess("新增订单成功", paymentOrder);
    }

    /**
     * 如果选择三级分销产品升级， 那么product_id需要填入三级分销的产品 id realamount手机充值用
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/type1/add")
    public @ResponseBody
    Object addPaymentOrderType1(HttpServletRequest request,
                                @RequestParam(value = "type", defaultValue = "0", required = false) String type,
                                @RequestParam(value = "desc", defaultValue = "", required = false) String desc,
                                @RequestParam(value = "desc_code", defaultValue = "", required = false) String descCode,
                                @RequestParam(value = "notify_url", defaultValue = "", required = false) String notifyUrl,
                                @RequestParam(value = "return_url", defaultValue = "", required = false) String returnUrl,
                                @RequestParam(value = "out_order_code", defaultValue = "", required = false) String outOrderCode,
                                @RequestParam(value = "userid") String userid,
                                @RequestParam(value = "openid", required = false) String openid,
                                @RequestParam(value = "amount") String amount,
                                // 车牌号
                                @RequestParam(value = "carNo", required = false) String carNo,
                                // 手机充值用的真实
                                @RequestParam(value = "realamount", required = false) String realamount,
                                // 充值手机号
                                @RequestParam(value = "phonebill", required = false) String phonebill,
                                @RequestParam(value = "remark", defaultValue = "", required = false) String remark,
                                @RequestParam(value = "channel_tag") String channeltag,
                                @RequestParam(value = "bank_card", required = false) String bankcard,
                                @RequestParam(value = "product_id", required = false) String prodid) {

        RestTemplate restTemplate = new RestTemplate();

        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/query/id";

        /* 根据的用户手机号码查询用户的基本信息 */
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("id", userid);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        long userId = resultObj.getLong("id");
        long brandid = resultObj.getLong("brandId");
        String brandname = resultObj.getString("brandname");
        String phone = resultObj.getString("phone");

        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/channel/query";

        PaymentOrder paymentOrder = new PaymentOrder();

        /* 根据的渠道标识或去渠道的相关信息 */
        if (channeltag.equalsIgnoreCase("JIEFUBAO") && !descCode.equals("RedPayment")) {

            requestEntity = new LinkedMultiValueMap<>();
            requestEntity.add("channel_tag", channeltag);

            result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================" + result);
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            long channelId = resultObj.getLong("id");
            String channelName = resultObj.getString("name");
            String channelTag = resultObj.getString("channelTag");
            String channelType = resultObj.getString("channelType");
            /* 根据用户的信息获取用户的渠道费率 */
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

            /* 根据的渠道标识或去渠道的相关信息 */
            requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("channel_id", channelId + "");
            requestEntity.add("user_id", userId + "");

            result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================" + result);
            jsonObject = JSONObject.fromObject(result);

            if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
                Map<String, String> map = new HashMap<String, String>();
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "亲.下单失败,臣妾已经尽力了,请重试!");
                return map;
            }

            resultObj = jsonObject.getJSONObject("result");
            String rate = resultObj.getString("rate");
            String extraFee = resultObj.getString("extraFee");

            paymentOrder.setChannelid(channelId);
            paymentOrder.setChannelname(channelName);
            paymentOrder.setChannelTag(channelTag);
            paymentOrder.setOpenid(openid);
            paymentOrder.setBankcard(bankcard);
            /* 默认是不自动清算 */
            paymentOrder.setAutoClearing("0");
            paymentOrder.setRate(new BigDecimal(rate));
            BigDecimal newextraFee = extraFee == null || extraFee.equalsIgnoreCase("")
                    || extraFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(extraFee);
            paymentOrder.setExtraFee(newextraFee);
            paymentOrder.setChannelType(channelType);
            /* 充值到账要扣除手续费的 */
            if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
                paymentOrder.setRealAmount(realamount != null ? new BigDecimal(realamount) : new BigDecimal(amount));
                paymentOrder.setChannelname("节付宝");
                paymentOrder.setChannelTag("JIEFUBAO");
                paymentOrder.setChannelType("1");
                paymentOrder.setPhoneBill(phonebill != null ? phonebill : "");
                paymentOrder.setCarNo(carNo != null ? carNo : "");
            }
        } else if (descCode.equals("RedPayment")) {

            paymentOrder.setChannelname("JIEFUBAO");
            paymentOrder.setChannelTag("JIEFUBAO");
            paymentOrder.setChannelType("0");
            paymentOrder.setRate(BigDecimal.ZERO);
            paymentOrder.setExtraFee(BigDecimal.ZERO);
            paymentOrder.setRealAmount(new BigDecimal(amount));
        }
        // String withdrawFee = resultObj.getString("withdrawFee");

        paymentOrder.setAmount(new BigDecimal(amount));
        paymentOrder.setUserid(userId);
        paymentOrder.setBrandid(brandid);
        paymentOrder.setBrandname(brandname);
        if (remark == null) {
            paymentOrder.setRemark("");
        } else {
            paymentOrder.setRemark(remark);
        }
        paymentOrder.setCreateTime(new Date());
        paymentOrder.setUpdateTime(new Date());
        paymentOrder.setDesc(desc);
        paymentOrder.setDescCode(descCode);
        paymentOrder.setOrdercode(UUIDGenerator.getUUID());
        paymentOrder.setPhone(phone);
        paymentOrder.setOutMerOrdercode(outOrderCode);
        paymentOrder.setType(type);
        paymentOrder.setOutNotifyUrl(notifyUrl);
        paymentOrder.setOutReturnUrl(returnUrl);
        paymentOrder.setStatus(CommonConstants.ORDER_READY);
        // BigDecimal newWithdrawFee = withdrawFee == null ||
        // withdrawFee.equalsIgnoreCase("") ||
        // withdrawFee.equalsIgnoreCase("null")? BigDecimal.ZERO : new
        // BigDecimal(withdrawFee);

        if (prodid != null && !prodid.equalsIgnoreCase("")) {
            paymentOrder.setThirdlevelid(prodid);
        }

        paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
        return CommonsUtil.returnOK(paymentOrder);
    }

    /**
     * 更新用户的订单
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/type1/update")
    public @ResponseBody
    Object updatePaymentOrderType1(HttpServletRequest request,
                                   @RequestParam(value = "order_code") String ordercode,
                                   @RequestParam(value = "status", required = false) String status,
                                   @RequestParam(value = "third_code", required = false) String thirdcode,
                                   @RequestParam(value = "direct_clearing", required = false, defaultValue = "0") String directclearing) {

        Map<String, Object> resultmap = new HashMap<>();

        if (Strings.hasText(status)) {
            if (paymentOrderBusiness.queryPaymentOrderBycodeAndStatus(ordercode, status) != null) {
                resultmap.put(CommonConstants.RESP_CODE, CommonConstants.ERRRO_ORDER_HAS_CHECKED);
                resultmap.put(CommonConstants.RESP_MESSAGE, "已经处理");
                return resultmap;
            }
        }

        /* 根据的用户手机号码查询用户的基本信息 */
        PaymentOrder order = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);

        if (thirdcode != null && !thirdcode.equalsIgnoreCase("")) {
            order.setThirdOrdercode(thirdcode);
        }
        order.setUpdateTime(new Date());

        if (status != null && !status.equalsIgnoreCase("")) {
            order.setStatus(status);
        }

        paymentOrderBusiness.mergePaymentOrder(order);

        /* 提现成功或者提现失败的情况下，都需要将金额首先解冻 */
        if (status != null && !status.equalsIgnoreCase("")
                && (status.equalsIgnoreCase("1") || status.equalsIgnoreCase("2"))) {

            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {

                if (order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {
                    RestTemplate restTemplate = new RestTemplate();
                    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    URI uri = util.getServiceUrl("user", "error url request!");
                    String url = uri.toString() + "/v1.0/user/account/freeze";
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("order_code", order.getOrdercode());
                    requestEntity.add("user_id", order.getUserid() + "");
                    requestEntity.add("amount", order.getRealAmount().toString());
                    requestEntity.add("add_or_sub", "1");
                    restTemplate.postForObject(url, requestEntity, String.class);

                }

            }

        }

        /* 充值的订单, 要发放分润， 发放积分 */
        if (status != null && !status.equalsIgnoreCase("") && status.equalsIgnoreCase(CommonConstants.ORDER_SUCCESS)) {
            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)
                    || order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)) {

                /* 表示是分润提现到余额 */
                if (order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {
                    if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
                        /* 首先更新用户的账户余额 **/
                        /* 如果通道自动清算的就不需要更新用户的账户了 */
                        if (order.getAutoClearing().equalsIgnoreCase("0")) {
                            RestTemplate restTemplate = new RestTemplate();
                            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                            URI uri = util.getServiceUrl("user", "error url request!");
                            String url = uri.toString() + "/v1.0/user/account/update";
                            requestEntity = new LinkedMultiValueMap<String, String>();
                            requestEntity.add("amount", order.getRealAmount().toString());
                            requestEntity.add("user_id", order.getUserid() + "");
                            requestEntity.add("order_code", order.getOrdercode());

                            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
                                /* 提现的时候减钱 */
                                requestEntity.add("addorsub", "1");

                            }
                            restTemplate.postForObject(url, requestEntity, String.class);

                            if (order.getDescCode() != null && order.getDescCode().equals("MobilePayment")) {
                                restTemplate = new RestTemplate();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
                                String result = restTemplate.getForObject(url, String.class);
                                JSONObject jsonObject = JSONObject.fromObject(result);
                                LOG.info("RESULT================MobilePayment" + result);
                                JSONObject resultbrand = jsonObject.getJSONObject("result");
                                /*
                                 * 添加贴牌的钱
                                 *****/
                                restTemplate = new RestTemplate();
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/account/update";
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("amount", order.getRealAmount().toString());
                                requestEntity.add("user_id", resultbrand.getString("manageid"));
                                requestEntity.add("order_code", order.getOrdercode());
                                /* 话费充值的时候向贴牌 */
                                requestEntity.add("addorsub", "0");
                                restTemplate.postForObject(url, requestEntity, String.class);

                            }
                        }

                    } else if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)) {

                        if (order.getDescCode() != null && order.getDescCode().equals("RedPayment")) {

                            /*
                             * 检查余额
                             ***/
                            RestTemplate restTemplate = new RestTemplate();
                            URI uri = util.getServiceUrl("user", "error url request!");
                            String url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
                            String result = restTemplate.getForObject(url, String.class);
                            JSONObject jsonObject = JSONObject.fromObject(result);
                            LOG.info("RESULT================purchaseShopping" + result);
                            JSONObject resultbrand = jsonObject.getJSONObject("result");

                            uri = util.getServiceUrl("user", "error url request!");
                            url = uri.toString() + "/v1.0/user/account/query/userId";
                            // **根据的用户手机号码查询用户的基本信息*/
                            LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                            requestEntity.add("user_id", resultbrand.getString("manageid"));
                            restTemplate = new RestTemplate();
                            result = restTemplate.postForObject(url, requestEntity, String.class);
                            LOG.info("RESULT================purchaseShopping" + result);
                            jsonObject = JSONObject.fromObject(result);
                            JSONObject UserAccount = jsonObject.getJSONObject("result");
                            BigDecimal balance = new BigDecimal("0");
                            if (UserAccount.containsKey("balance")) {
                                balance = new BigDecimal(UserAccount.getString("balance"));
                            }
                            if (balance.compareTo(order.getRealAmount()) == -1) {
                                resultmap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                                resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
                                return resultmap;

                            }

                            /* 添加用户钱 */
                            {
                                restTemplate = new RestTemplate();
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/account/update";
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("amount", order.getRealAmount().toString());
                                requestEntity.add("user_id", order.getUserid() + "");
                                requestEntity.add("order_code", order.getOrdercode());
                                restTemplate.postForObject(url, requestEntity, String.class);
                            }

                            /*
                             * 减去贴牌的钱
                             *****/
                            {
                                restTemplate = new RestTemplate();
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/account/update";
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("amount", order.getRealAmount().toString());
                                requestEntity.add("user_id", resultbrand.getString("manageid"));
                                requestEntity.add("order_code", order.getOrdercode());
                                /* 提现的时候减钱 */
                                requestEntity.add("addorsub", "1");
                                restTemplate.postForObject(url, requestEntity, String.class);

                            }

                        }

                    }

                }

            }

            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
                /* 循环处理用户的分润 */
                rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
                        order.getBrandid());
            }

        }
        resultmap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
        return resultmap;
    }

    /**
     * 更新用户的订单
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/sendrebate")
    public @ResponseBody
    Object sendRebate(HttpServletRequest request,
                      @RequestParam(value = "order_code") String ordercode) {
        Map resultmap = new HashMap();
        /* 根据的用户手机号码查询用户的基本信息 */
        PaymentOrder order = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);
        /* 循环处理用户的分润 */
        rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
                order.getBrandid());
        resultmap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
        return resultmap;

    }

    /**
     * 更新用户的订单
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update")
    public @ResponseBody
    Object updatePaymentOrder(
            @RequestParam(value = "order_code") String ordercode,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "third_code", required = false) String thirdcode,
            @RequestParam(value = "direct_clearing", required = false, defaultValue = "0") String directclearing) {

        Map<String, Object> resultmap = new HashMap<>();
        if (status != null && !status.equalsIgnoreCase("")) {

            if (paymentOrderBusiness.queryPaymentOrderBycodeAndStatus(ordercode, status) != null) {
                resultmap.put(CommonConstants.RESP_CODE, CommonConstants.ERRRO_ORDER_HAS_CHECKED);
                resultmap.put(CommonConstants.RESP_MESSAGE, "已经处理");
                return resultmap;
            }

        }

        /* 根据的用户手机号码查询用户的基本信息 */
        PaymentOrder order = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);

        if (order == null) {
            resultmap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultmap.put(CommonConstants.RESP_MESSAGE, "未获取到该订单!");
            return resultmap;

        }

        if (thirdcode != null && !thirdcode.equalsIgnoreCase("")) {
            order.setThirdOrdercode(thirdcode);
        }
        order.setUpdateTime(new Date());

        /* 如果状态是成功, 判断交易类型 */
        if (status != null && !status.equalsIgnoreCase("") && status.equalsIgnoreCase("1")
                && !order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)
                && !order.getType().equalsIgnoreCase(ORDER_TYPE_WITHDRAW)) {

            /* 判断通道的结算类型 */
            String clearingType = order.getChannelType();

            if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_T_0)) {

                /* 判断当前是否是休息日 */
                Calendar today = Calendar.getInstance();
                if (today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
                        || today.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {

                    status = "4";

                } else {
                    status = "1";
                }

            } else if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_T_1)) {

                /* 判断当前是否是休息日 */
                Calendar today = Calendar.getInstance();
                if (today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
                        || today.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {

                    status = "4";
                } else {

                    /* 判断当前日期和订单的生成日期是否相隔24小时 */
                    int day = getIntervalDays(order.getCreateTime(), today.getTime());
                    if (day > 0) {
                        status = "1";
                    } else {
                        status = "4";
                    }
                }

            } else if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_D_0)) {

                status = "1";

            } else if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_D_1)) {

                Calendar today = Calendar.getInstance();
                /* 判断当前日期和订单的生成日期是否相隔24小时 */
                int day = getIntervalDays(order.getCreateTime(), today.getTime());
                if (day > 0) {
                    status = "1";
                } else {
                    status = "4";

                }

            } else {

                status = "1";

            }

        }

        if (status != null && !status.equalsIgnoreCase("")) {
            order.setStatus(status);
        }
        if (status != null && !status.equalsIgnoreCase("") && status.equals("4")) {
            // 推送消息
        }
        paymentOrderBusiness.mergePaymentOrder(order);

        /* 提现成功或者提现失败的情况下，都需要将金额首先解冻 */
        if (status != null && !status.equalsIgnoreCase("")
                && (status.equalsIgnoreCase("1") || status.equalsIgnoreCase("2"))) {

            if (order.getType().equalsIgnoreCase(ORDER_TYPE_WITHDRAW)) {

                if (!order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {

                    RestTemplate restTemplate = new RestTemplate();
                    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    URI uri = util.getServiceUrl("user", "error url request!");
                    String url = uri.toString() + "/v1.0/user/account/freeze";
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("order_code", order.getOrdercode());
                    requestEntity.add("user_id", order.getUserid() + "");
                    requestEntity.add("amount", order.getAmount().toString());
                    requestEntity.add("add_or_sub", "1");
                    restTemplate.postForObject(url, requestEntity, String.class);

                } else {

                    RestTemplate restTemplate = new RestTemplate();
                    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    URI uri = util.getServiceUrl("user", "error url request!");
                    String url = uri.toString() + "/v1.0/user/account/rebate/unfreeze";
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("order_code", order.getOrdercode());
                    requestEntity.add("user_id", order.getUserid() + "");
                    requestEntity.add("amount", order.getAmount().toString());
                    requestEntity.add("add_or_sub", "1");
                    restTemplate.postForObject(url, requestEntity, String.class);

                }

            }

        }

        /* 充值的订单, 要发放分润， 发放积分 */
        if (status != null && !status.equalsIgnoreCase("") && status.equalsIgnoreCase(CommonConstants.ORDER_SUCCESS)) {
            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)
                    || order.getType().equalsIgnoreCase(ORDER_TYPE_WITHDRAW)) {

                /* 表示是分润提现到余额 */
                if (order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {

                    /* 首先更新用户的账户余额 **/
                    RestTemplate restTemplate = new RestTemplate();
                    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    URI uri = util.getServiceUrl("user", "error url request!");
                    String url = uri.toString() + "/v1.0/user/account/rebate/update";
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("amount", order.getRealAmount().toString());
                    requestEntity.add("user_id", order.getUserid() + "");
                    requestEntity.add("order_code", order.getOrdercode());

                    restTemplate.postForObject(url, requestEntity, String.class);

                } else {

                    /* 首先更新用户的账户余额 **/
                    /* 如果通道自动清算的就不需要更新用户的账户了 */
                    if (order.getAutoClearing().equalsIgnoreCase("0")) {
                        RestTemplate restTemplate = new RestTemplate();
                        MultiValueMap<String, String> requestEntity;
                        URI uri = util.getServiceUrl("user", "error url request!");
                        String url = uri.toString() + "/v1.0/user/account/update";
                        requestEntity = new LinkedMultiValueMap<>();
                        requestEntity.add("user_id", order.getUserid() + "");
                        requestEntity.add("order_code", order.getOrdercode());
                        if (order.getType().equalsIgnoreCase(ORDER_TYPE_WITHDRAW)) {
                            requestEntity.add("amount", order.getAmount().toString());
                            /* 提现的时候减钱 */
                            requestEntity.add("addorsub", "1");
                        } else {
                            requestEntity.add("amount", order.getRealAmount().toString());
                        }

                        restTemplate.postForObject(url, requestEntity, String.class);
                    }
                }

            }
            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)) {
                /* 循环处理用户的分润 */
                rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
                        order.getBrandid());

            }

            /* 如果是支付订单 */
            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)
                    && (order.getDescCode() == null || !order.getDescCode().equals("shopping"))) {

                /* 更新用户的等级 */
                if (order.getThirdlevelid() != null && !order.getThirdlevelid().equalsIgnoreCase("")) {

                    /* 获取用户的等级信息 */
                    RestTemplate restTemplate = new RestTemplate();
                    // MultiValueMap<String, String> requestEntity = new
                    // LinkedMultiValueMap<String, String>();
                    URI uri = util.getServiceUrl("user", "error url request!");
                    String url = uri.toString() + "/v1.0/user/thirdlevel/prod/query/" + order.getThirdlevelid();
                    String result = restTemplate.getForObject(url, String.class);
                    JSONObject jsonObject = JSONObject.fromObject(result);
                    JSONObject objResObject = jsonObject.getJSONObject("result");
                    String grade = objResObject.getString("grade");

                    /* 更新用户的等级 **/
                    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    url = uri.toString() + "/v1.0/user/grade/update";
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("grade", grade);
                    requestEntity.add("id", order.getUserid() + "");
                    result = restTemplate.postForObject(url, requestEntity, String.class);

                    /*
                     * url = uri.toString() +
                     * "/v1.0/user/thirdlevel/prod/rate/"+order.getThirdlevelid(
                     * ); result = restTemplate.getForObject(url, String.class);
                     * jsonObject = JSONObject.fromObject(result); JSONArray
                     * jsonArray = jsonObject.getJSONArray("result");
                     *
                     * for(int i=0;i<jsonArray.size();i++){
                     *
                     *//* 更新用户的费率 *//*
                     * requestEntity = new
                     * LinkedMultiValueMap<String, String>();
                     * url = uri.toString() +
                     * "/v1.0/user/channel/rate/update/userid";
                     * requestEntity = new
                     * LinkedMultiValueMap<String, String>();
                     * requestEntity.add("user_id",
                     * order.getUserid()+"");
                     * requestEntity.add("channel_id",
                     * jsonArray.optJSONObject(i).optString(
                     * "channelId")); requestEntity.add("rate",
                     * jsonArray.optJSONObject(i).optString(
                     * "rate")); result =
                     * restTemplate.postForObject(url,
                     * requestEntity, String.class);
                     *
                     * }
                     */
                    restTemplate = new RestTemplate();
                    uri = util.getServiceUrl("user", "error url request!");
                    url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
                    result = restTemplate.getForObject(url, String.class);
                    jsonObject = JSONObject.fromObject(result);

                    jsonObject = jsonObject.getJSONObject(CommonConstants.RESULT);
                    int isNewRebate = jsonObject.getInt("isNewRebate");
                    if (isNewRebate == 0) {
                        /* 如果是支付订单，返佣，并且设置用户的刷卡费率 */
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/thirdlevel/ratio/query/" + order.getBrandid();
                        result = restTemplate.getForObject(url, String.class);
                        jsonObject = JSONObject.fromObject(result);
                        JSONArray jsonArray = jsonObject.getJSONArray("result");
                        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            map.put(jsonArray.optJSONObject(i).optString("preLevel"), new BigDecimal(jsonArray.optJSONObject(i).optString("ratio")));
                        }
                        /* 计算用户三级返佣 */
                        /* 三级分销的金额也是扣除手续费以后的金额 */
                        sendThirdDistribution(ordercode, order.getUserid(), order.getPhone(), order.getRealAmount(), map, order.getBrandid());
                    } else if (isNewRebate == 1) {
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/thirdlevel/ratio/query/by/thirdlevelid";
                        requestEntity = new LinkedMultiValueMap<String, String>();
                        requestEntity.add("brandId", order.getBrandid() + "");
                        requestEntity.add("thirdLevelId", order.getThirdlevelid());
                        result = restTemplate.postForObject(url, requestEntity, String.class);
                        jsonObject = JSONObject.fromObject(result);
                        JSONArray jsonArray = jsonObject.getJSONArray(CommonConstants.RESULT);
                        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            map.put(jsonArray.optJSONObject(i).optString("preLevel"), new BigDecimal(jsonArray.optJSONObject(i).optString("ratio")));
                        }
                        sendThirdDistributionNew(ordercode, order.getUserid(), order.getPhone(), order.getRealAmount(), map, order.getBrandid());
                    }
                }
            } else if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY) && order.getDescCode() != null
                    && order.getDescCode().equals("shopping")) {
                /* 循环处理用户的分润 */
                rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
                        order.getBrandid());
                /* 转给贴牌商 **/
                {
                    /* 通过用户ID判定是否为贴牌 */
                    RestTemplate restTemplate = new RestTemplate();
                    URI uri = util.getServiceUrl("user", "error url request!");
                    String url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
                    String result = restTemplate.getForObject(url, String.class);
                    JSONObject jsonObject = JSONObject.fromObject(result);
                    LOG.info("RESULT================purchaseShopping" + result);
                    JSONObject resultbrand = jsonObject.getJSONObject("result");

                    uri = util.getServiceUrl("user", "error url request!");
                    url = uri.toString() + "/v1.0/user/query/id";
                    // **根据的用户手机号码查询用户的基本信息*/
                    LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("id", resultbrand.getString("manageid"));
                    restTemplate = new RestTemplate();
                    result = restTemplate.postForObject(url, requestEntity, String.class);
                    LOG.info("RESULT================purchaseShopping" + result);
                    jsonObject = JSONObject.fromObject(result);
                    JSONObject resultObju = jsonObject.getJSONObject("result");
                    String phone = null;
                    if (resultObju.containsKey("phone")) {
                        phone = resultObju.getString("phone");
                    }
                    /* 计算分润的钱 */
                    BigDecimal rebate = order.getRealAmount().setScale(2, BigDecimal.ROUND_HALF_UP);

                    /* 存贮分润记录明细 */
                    ProfitRecord profitRecord = new ProfitRecord();
                    profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                    profitRecord.setAcqAmount(rebate);
                    profitRecord.setAcqphone(phone);
                    profitRecord.setAcqrate(new BigDecimal("0.0"));
                    profitRecord.setAcquserid(Long.parseLong(resultObju.getString("id")));
                    profitRecord.setAmount(order.getRealAmount());
                    profitRecord.setCreateTime(new Date());
                    profitRecord.setOrdercode(ordercode);
                    profitRecord.setOriphone(order.getPhone());
                    profitRecord.setOrirate(order.getRate());
                    profitRecord.setOriuserid(order.getUserid());
                    profitRecord.setRemark("产品剩余金额");
                    profitRecord.setScale(BigDecimal.ONE);
                    profitRecord.setType("3");
                    profitRecordBusiness.merge(profitRecord);

                    /* 存储 用户的分润记录 */
                    restTemplate = new RestTemplate();
                    uri = util.getServiceUrl("user", "error url request!");
                    url = uri.toString() + "/v1.0/user/rebate/update";
                    /* 根据的渠道标识或去渠道的相关信息 */
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("rebate_amount", rebate.toString());
                    requestEntity.add("user_id", resultObju.getString("id"));
                    requestEntity.add("order_code", ordercode);
                    result = restTemplate.postForObject(url, requestEntity, String.class);

                }

            }
            LOG.info("===============444444444444444444");

            if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)
                    || order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
                /* 发放积分 */
                sendCoin(ordercode, order.getType(), order.getUserid(), order.getPhone(), order.getBrandid(),
                        order.getBrandname(), order.getAmount());
            }
        }

        resultmap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
        return resultmap;
    }


    /**
     * 发放用户的返佣 新逻辑
     **/
    private void sendThirdDistributionNew(String ordercode, long userid, String phone, BigDecimal amount, Map<String, BigDecimal> map, long brandid) {
        long oriUserId = userid;
        int i = 1;

        long lowerUserId = userid;
        String lowerPhone = phone;

        BigDecimal remainingAmount = amount;
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("user", "user url request!");
        String url = uri.toString() + "/v1.0/user/query/id";

        /* 根据的用户手机号码查询用户的基本信息 */
        requestEntity.add("id", userid + "");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================/v1.0/user/query/id:" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        long preUserId = resultObj.getLong("preUserId");
        String preUserPhone = resultObj.getString("preUserPhone");
        String oriGrade = resultObj.getString("grade");


        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + brandid;
        result = restTemplate.getForObject(url, String.class);

        /* 根据的渠道标识或去渠道的相关信息 */
        jsonObject = JSONObject.fromObject(result);
        resultObj = jsonObject.getJSONObject("result");
        String manageId = resultObj.getString("manageid");
        int rebateCount = resultObj.getInt("rebateCount");
        BigDecimal rate = null;
        BigDecimal rate1 = null;
        BigDecimal rate2 = null;
        BigDecimal rate3 = null;
        /* 根据userid 找到上级， 如果上级的等级大于等于他就发放返佣，然后继续循环方法 */
        while (true) {
            if (i > rebateCount) {
                break;
            }
            if (preUserId != 0) {
                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("user", "error url request!");
                url = uri.toString() + "/v1.0/user/query/id";
                requestEntity = new LinkedMultiValueMap<String, String>();
                requestEntity.add("id", preUserId + "");
                result = restTemplate.postForObject(url, requestEntity, String.class);
                LOG.info("RESULT================" + result);
                jsonObject = JSONObject.fromObject(result);
                resultObj = jsonObject.getJSONObject("result");
                String preGrade = resultObj.getString("grade");
                preUserPhone = resultObj.getString("phone");
                long xPreUserId = resultObj.getLong("preUserId");
                /* 如果上级没有购买三级分销或者前面的三级分销等级比自己的等级低 */
                if ("0".equals(preGrade) || new BigDecimal(preGrade).compareTo(new BigDecimal(oriGrade)) < 0) {
                    preUserId = xPreUserId;
                    continue;
                } else {
                    if (preUserId == Long.valueOf(manageId)) {
                        break;
                    }
                    if (i == 1) {
                        rate1 = map.get(preGrade);
                        rate = rate1;
                    }
                    if (i == 2) {
                        rate2 = map.get(preGrade).subtract(rate1);
                        if (rate2.compareTo(BigDecimal.ZERO) <= 0) {
                            preUserId = xPreUserId;
                            continue;
                        }
                        rate = rate2;
                        rate2 = map.get(preGrade);
                    }
                    if (i == 3) {
                        rate3 = map.get(preGrade).subtract(rate2);
                        if (rate3.compareTo(BigDecimal.ZERO) <= 0) {
                            preUserId = xPreUserId;
                            continue;
                        }
                        rate = rate3;
                    }
                    /* 存贮分润记录明细 */
                    DistributionRecord profitRecord = new DistributionRecord();
                    profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                    profitRecord.setAcqphone(preUserPhone);
                    profitRecord.setAcquserid(preUserId);
                    profitRecord.setAmount(amount);
                    profitRecord.setAcqAmount(rate.multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
                    profitRecord.setAcqratio(map.get(preGrade));
                    profitRecord.setCreateTime(new Date());
                    profitRecord.setOrdercode(ordercode);
                    profitRecord.setOriphone(lowerPhone);
                    profitRecord.setOriuserid(lowerUserId);
                    profitRecord.setRemark("获得下级用户返佣");
                    profitRecordBusiness.merge(profitRecord);

                    /* 修改用户的分润 */
                    restTemplate = new RestTemplate();
                    uri = util.getServiceUrl("user", "error url request!");
                    url = uri.toString() + "/v1.0/user/rebate/update";
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("rebate_amount", rate.multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    requestEntity.add("user_id", preUserId + "");
                    requestEntity.add("order_code", ordercode);
                    requestEntity.add("order_type", "1");
                    result = restTemplate.postForObject(url, requestEntity, String.class);
                    remainingAmount = remainingAmount.subtract(rate.multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                lowerUserId = preUserId;
                lowerPhone = preUserPhone;
                preUserId = xPreUserId;
                i++;
            } else {
                break;
            }
        }

//		将剩余的产品金额给贴牌商
        if (remainingAmount.compareTo(BigDecimal.ZERO) > 0) {
            restTemplate = new RestTemplate();
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/query/id";
            /* 根据的渠道标识或去渠道的相关信息 */
            requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("id", manageId);
            result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================/v1.0/user/query/id:" + result);
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            String managephone = resultObj.getString("phone");

            /* 存贮分润记录明细 */
            ProfitRecord profitRecord = new ProfitRecord();
            profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
            profitRecord.setAcqAmount(remainingAmount);
            profitRecord.setAcqphone(managephone);
            profitRecord.setAcquserid(Long.parseLong(manageId));
            profitRecord.setAmount(amount);
            profitRecord.setCreateTime(new Date());
            profitRecord.setOrdercode(ordercode);
            profitRecord.setOriphone(phone);
            profitRecord.setOriuserid(userid);
            profitRecord.setRemark("产品剩余分润");
            profitRecord.setType("2");
            profitRecord.setScale(BigDecimal.ONE);
            profitRecordBusiness.merge(profitRecord);

//			增加贴牌商余额
            restTemplate = new RestTemplate();
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/rebate/update";
            requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("rebate_amount", remainingAmount.toString());
            requestEntity.add("user_id", manageId);
            requestEntity.add("order_code", ordercode);
            requestEntity.add("order_type", "1");
            result = restTemplate.postForObject(url, requestEntity, String.class);
        }
    }


    /**
     * 发放用户的返佣
     **/
    private void sendThirdDistribution(String ordercode, long userid, String phone, BigDecimal amount,
                                       Map<String, BigDecimal> map, long brandid) {

        long oriuserid = userid;

        int i = 1;

        BigDecimal remainingAmount = amount;

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/query/id";

        /* 根据的用户手机号码查询用户的基本信息 */
        requestEntity.add("id", userid + "");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        long preuserid = resultObj.getLong("preUserId");
        String preuserphone = resultObj.getString("preUserPhone");
        String origrade = resultObj.getString("grade");
        phone = resultObj.getString("phone");
        /* 根据userid 找到上级， 如果上级的费率比他低就发放分润，然后继续循环方法 */
        while (true) {
            if (i > 3) {
                break;
            }

            /* 用户证明有上级用户 */
            if (preuserid != 0) {
                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("user", "error url request!");
                url = uri.toString() + "/v1.0/user/query/id";
                requestEntity = new LinkedMultiValueMap<String, String>();
                requestEntity.add("id", preuserid + "");
                result = restTemplate.postForObject(url, requestEntity, String.class);
                LOG.info("RESULT================" + result);
                jsonObject = JSONObject.fromObject(result);
                resultObj = jsonObject.getJSONObject("result");
                preuserphone = resultObj.getString("phone");
                String grade = resultObj.getString("grade");
                long xpreuserid = resultObj.getLong("preUserId");
                String xprephone = resultObj.getString("preUserPhone");
                /* 如果上级没有购买三级分销或者前面的三级分销等级比自己的等级低 */
                if (grade.equalsIgnoreCase("0") || new BigDecimal(grade).compareTo(new BigDecimal(origrade)) < 0) {
                    preuserphone = xprephone;
                    preuserid = xpreuserid;
                    continue;
                } else {
                    if (map.get(grade) != null) {
                        /* 存贮分润记录明细 */
                        DistributionRecord profitRecord = new DistributionRecord();
                        // profitRecord.setAcqAmount(rebate);
                        profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                        profitRecord.setAcqphone(preuserphone);
                        profitRecord.setAcquserid(preuserid);
                        profitRecord.setAmount(amount);
                        profitRecord
                                .setAcqAmount(map.get(grade).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
                        profitRecord.setAcqratio(map.get(grade));
                        profitRecord.setCreateTime(new Date());
                        profitRecord.setOrdercode(ordercode);
                        profitRecord.setOriphone(phone);
                        profitRecord.setOriuserid(oriuserid);
                        profitRecord.setRemark("");
                        profitRecordBusiness.merge(profitRecord);

                        /* 存储 用户的分润记录 */
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/rebate/update";
                        /* 根据的渠道标识或去渠道的相关信息 */
                        requestEntity = new LinkedMultiValueMap<String, String>();
                        requestEntity.add("rebate_amount",
                                map.get(grade).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        requestEntity.add("user_id", preuserid + "");
                        requestEntity.add("order_code", ordercode);
                        requestEntity.add("order_type", "1");
                        result = restTemplate.postForObject(url, requestEntity, String.class);

                        remainingAmount = remainingAmount
                                .subtract(map.get(grade).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                }

                i++;

                preuserphone = xprephone;
                preuserid = xpreuserid;

                /* 当前用户作为下一次循环的初始用户了 */
                // userid = preuserid;

            } else {

                break;
            }
        }

        /* 讲剩余的产品金额给贴牌商 */
        if (remainingAmount.compareTo(BigDecimal.ZERO) > 0) {

            restTemplate = new RestTemplate();
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + brandid;
            result = restTemplate.getForObject(url, String.class);

            /* 根据的渠道标识或去渠道的相关信息 */
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            String manageid = resultObj.getString("manageid");

            /* 根据manageid获取用户 */
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/query/id";
            /* 根据的渠道标识或去渠道的相关信息 */
            requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("id", manageid);
            result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================" + result);
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            String managephone = resultObj.getString("phone");

            /* 存贮分润记录明细 */
            ProfitRecord profitRecord = new ProfitRecord();
            profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
            ;
            profitRecord.setAcqAmount(remainingAmount);
            profitRecord.setAcqphone(managephone);
            profitRecord.setAcquserid(Long.parseLong(manageid));
            profitRecord.setAmount(amount);
            profitRecord.setCreateTime(new Date());
            profitRecord.setOrdercode(ordercode);
            profitRecord.setOriphone(phone);
            profitRecord.setOriuserid(userid);
            profitRecord.setRemark("产品剩余分润");
            profitRecord.setType("2");
            profitRecord.setScale(BigDecimal.ONE);
            profitRecordBusiness.merge(profitRecord);

            /* 存储 用户的分润记录 */
            restTemplate = new RestTemplate();
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/rebate/update";
            /* 根据的渠道标识或去渠道的相关信息 */
            requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("rebate_amount", remainingAmount.toString());
            requestEntity.add("user_id", manageid);
            requestEntity.add("order_code", ordercode);
            requestEntity.add("order_type", "1");
            result = restTemplate.postForObject(url, requestEntity, String.class);

        }

    }

    /**
     * 发放用户的积分
     */
    private void sendCoin(String ordercode, String type, long userid, String phone, long brandid, String brandname,
                          BigDecimal amount) {

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/brandcoin/query";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("brand_id", brandid + "");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        String ratio = resultObj.getString("ratio");

        BigDecimal coinBd = amount.divide(new BigDecimal(ratio), RoundingMode.DOWN);

        CoinRecord coinRecord = new CoinRecord();
        coinRecord.setBrand_id(brandid);
        coinRecord.setCoin(coinBd.intValue());
        coinRecord.setCreateTime(new Date());
        coinRecord.setOrdercode(ordercode);
        coinRecord.setBrand_name(brandname);
        if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
            coinRecord.setRemark("消费返积分");
        } else {
            coinRecord.setRemark("充值返积分");
        }
        coinRecord.setType(CommonConstants.COIN_TYPE_ADD);
        coinRecord.setUserid(userid);
        coinRecord.setUserphone(phone);
        coinRecordBusiness.mergeCoinRecord(coinRecord);

        /* 存储 用户的积分记录 */
        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/coin/update/userid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("user_id", userid + "");
        requestEntity.add("coin", coinBd.intValue() + "");
        requestEntity.add("order_code", ordercode);
        result = restTemplate.postForObject(url, requestEntity, String.class);
    }

    private void rebate2(String ordercode, long userid, long channelId, BigDecimal amount, BigDecimal currate,
                         long brandid) {
        boolean isCancel = false;
        boolean isequalRebateRate = false;
        String equalRebateRate = "";

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/query/id";

        /* 根据的用户手机号码查询用户的基本信息 */
        requestEntity.add("id", userid + "");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        String grade = resultObj.getString("grade");
        Integer equalGrade = Integer.valueOf("0".equals(grade) ? "1" : grade);
        /* 根据userid 找到上级， 如果上级的费率比他低就发放分润，然后继续循环方法 */
        while (true) {

            if (isCancel) {
                break;
            }

            restTemplate = new RestTemplate();
            requestEntity = new LinkedMultiValueMap<String, String>();
            restTemplate = new RestTemplate();
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/query/id";

            /* 根据的用户手机号码查询用户的基本信息 */
            requestEntity.add("id", userid + "");
            result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================" + result);
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            String oriphone = resultObj.getString("phone");
            long preuserid = resultObj.getLong("preUserId");
            grade = resultObj.getString("grade");

            String preuserphone = resultObj.getString("preUserPhone");

            /* 用户证明有上级用户 */
            if (preuserid != 0 && preuserphone != null && !preuserphone.equalsIgnoreCase("")) {

                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("user", "error url request!");
                url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

                /* 根据的渠道标识或去渠道的相关信息 */
                requestEntity = new LinkedMultiValueMap<String, String>();
                requestEntity.add("channel_id", channelId + "");
                requestEntity.add("user_id", preuserid + "");

                result = restTemplate.postForObject(url, requestEntity, String.class);
                LOG.info("RESULT================" + result);
                jsonObject = JSONObject.fromObject(result);

                if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
                    LOG.error("亲.无渠道费率,请配置渠道费率哦!======userId:" + preuserid + "channelId:" + channelId);
//					throw new RuntimeException("亲.无渠道费率,请配置渠道费率哦!");
                    userid = preuserid;
                    continue;
                }

                resultObj = jsonObject.getJSONObject("result");
                String rate = resultObj.getString("rate");

                /* 证明上级的费率小于当前 */
                if (new BigDecimal(rate).compareTo(currate) < 0) {

                    /* 计算分润的钱 */
                    BigDecimal rebate = (currate.subtract(new BigDecimal(rate))).multiply(amount).setScale(2,
                            BigDecimal.ROUND_HALF_UP);
                    if (rebate.toString().equals("0.00")) {
                        /* 当前用户作为下一次循环的初始用户了 */
                        userid = preuserid;
                        currate = new BigDecimal(rate);
                        continue;
                    }
                    /* 存贮分润记录明细 */
                    ProfitRecord profitRecord = new ProfitRecord();
                    profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                    ;
                    profitRecord.setAcqAmount(rebate);
                    profitRecord.setAcqphone(preuserphone);
                    profitRecord.setAcqrate(new BigDecimal(rate));
                    profitRecord.setAcquserid(preuserid);
                    profitRecord.setAmount(amount);
                    profitRecord.setCreateTime(new Date());
                    profitRecord.setOrdercode(ordercode);
                    profitRecord.setOriphone(oriphone);
                    profitRecord.setOrirate(currate);
                    profitRecord.setOriuserid(userid);
                    profitRecord.setRemark("差额费率分润");
                    profitRecord.setScale(BigDecimal.ONE);
                    profitRecord.setType("0");
                    profitRecordBusiness.merge(profitRecord);

                    /* 存储 用户的分润记录 */
                    restTemplate = new RestTemplate();
                    uri = util.getServiceUrl("user", "error url request!");
                    url = uri.toString() + "/v1.0/user/rebate/update";
                    /* 根据的渠道标识或去渠道的相关信息 */
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("rebate_amount", rebate.toString());
                    requestEntity.add("user_id", preuserid + "");
                    requestEntity.add("order_code", ordercode);
                    result = restTemplate.postForObject(url, requestEntity, String.class);

                    /* 当前用户作为下一次循环的初始用户了 */
                    userid = preuserid;
                    currate = new BigDecimal(rate);
                    continue;

                } else {

                    if (!isequalRebateRate) {
                        /* 根据品牌id获取同级的分润比率 */
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + brandid;
                        result = restTemplate.getForObject(url, String.class);
                        jsonObject = JSONObject.fromObject(result);
                        resultObj = jsonObject.getJSONObject("result");
                        equalRebateRate = resultObj.getString("equalRebateRate");

                        isequalRebateRate = true;
                    }
                    /* 寻找比自己费率低的 */


                    while (true) {

                        /* 先发放同级分润 */
                        if (equalRebateRate != null && !equalRebateRate.equalsIgnoreCase("")
                                && !equalRebateRate.equalsIgnoreCase("null")) {

                            if (new BigDecimal(equalRebateRate).compareTo(BigDecimal.ZERO) > 0) {

                                restTemplate = new RestTemplate();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/query/id";
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("id", preuserid + "");
                                result = restTemplate.postForObject(url, requestEntity, String.class);
                                LOG.info("RESULT================" + result);
                                jsonObject = JSONObject.fromObject(result);
                                resultObj = jsonObject.getJSONObject("result");
                                String pregrade = resultObj.getString("grade");
                                if (equalGrade.equals(Integer.valueOf(pregrade)) && Integer.parseInt(pregrade) == Integer.parseInt(grade)) {
                                    equalGrade = equalGrade + 1;

                                    uri = util.getServiceUrl("user", "error url request!");
                                    url = uri.toString() + "/v1.0/user/rebate/query/sumrebatepremonth";
                                    requestEntity = new LinkedMultiValueMap<String, String>();
                                    requestEntity.add("user_id", String.valueOf(userid));
                                    restTemplate = new RestTemplate();
                                    result = restTemplate.postForObject(url, requestEntity, String.class);
                                    LOG.info("RESULT================purchaseShopping" + result);
                                    jsonObject = JSONObject.fromObject(result);
                                    LOG.info("jsonObject================" + jsonObject);
                                    BigDecimal currentrebate = new BigDecimal("0");
                                    if (jsonObject.containsKey("result")) {
                                        JSONObject UserAccount = jsonObject.getJSONObject("result");
                                        currentrebate = new BigDecimal(UserAccount.getString("monthRebate"));
                                    }
                                    uri = util.getServiceUrl("user", "error url request!");
                                    url = uri.toString() + "/v1.0/user/rebate/query/sumrebatepremonth";
                                    requestEntity = new LinkedMultiValueMap<String, String>();
                                    requestEntity.add("user_id", String.valueOf(preuserid));
                                    restTemplate = new RestTemplate();
                                    result = restTemplate.postForObject(url, requestEntity, String.class);
                                    LOG.info("RESULT================purchaseShopping" + result);
                                    jsonObject = JSONObject.fromObject(result);
                                    LOG.info("jsonObject================" + jsonObject);
                                    BigDecimal prerebate = new BigDecimal("0");
                                    if (jsonObject.containsKey("result")) {
                                        JSONObject UserAccount = jsonObject.getJSONObject("result");
                                        prerebate = new BigDecimal(UserAccount.getString("monthRebate"));
                                    }
                                    /* 计算分润的钱 */
                                    BigDecimal rebate = new BigDecimal("0");
                                    if (currentrebate.compareTo(prerebate) < 0) {
                                        rebate = new BigDecimal(equalRebateRate).multiply(currentrebate).setScale(2,
                                                BigDecimal.ROUND_HALF_UP);
                                    } else {
                                        rebate = new BigDecimal(equalRebateRate).multiply(prerebate).setScale(2,
                                                BigDecimal.ROUND_HALF_UP);
                                    }
                                    LOG.info("===============用户ID" + preuserid + "," + "获得分润:" + rebate.toString() + "===============");
                                    if (rebate.toString().equals("0.00")) {
                                        userid = preuserid;
                                        currate = new BigDecimal(rate);
                                        break;
                                    }
                                    /* 存贮分润记录明细 */
                                    ProfitRecord profitRecord = new ProfitRecord();
                                    profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                                    profitRecord.setAcqAmount(rebate);
                                    profitRecord.setAcqphone(preuserphone);
                                    profitRecord.setAcqrate(new BigDecimal(rate));
                                    profitRecord.setAcquserid(preuserid);
                                    profitRecord.setAmount(amount);
                                    profitRecord.setCreateTime(new Date());
                                    profitRecord.setOrdercode(ordercode);
                                    profitRecord.setOriphone(oriphone);
                                    profitRecord.setOrirate(currate);
                                    profitRecord.setOriuserid(userid);
                                    profitRecord.setRemark("平级分润");
                                    profitRecord.setScale(BigDecimal.ONE);
                                    profitRecord.setType("3");
                                    profitRecordBusiness.merge(profitRecord);

                                    /* 存储 用户的分润记录 */
                                    restTemplate = new RestTemplate();
                                    uri = util.getServiceUrl("user", "error url request!");
                                    url = uri.toString() + "/v1.0/user/rebate/update";
                                    /* 根据的渠道标识或去渠道的相关信息 */
                                    requestEntity = new LinkedMultiValueMap<String, String>();
                                    requestEntity.add("rebate_amount", rebate.toString());
                                    requestEntity.add("user_id", preuserid + "");
                                    requestEntity.add("order_code", ordercode);
                                    result = restTemplate.postForObject(url, requestEntity, String.class);


                                    LOG.info("平级分润================================受益人:" + preuserid + ",等级:" + pregrade + ",平级等级:" + equalGrade);

                                }
                            }
                        }
                        restTemplate = new RestTemplate();
                        requestEntity = new LinkedMultiValueMap<String, String>();
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/query/id";

                        /* 根据的用户手机号码查询用户的基本信息 */
                        requestEntity.add("id", preuserid + "");
                        result = restTemplate.postForObject(url, requestEntity, String.class);
                        LOG.info("RESULT================" + result);
                        jsonObject = JSONObject.fromObject(result);
                        resultObj = jsonObject.getJSONObject("result");
                        preuserid = resultObj.getLong("preUserId");
                        grade = resultObj.getString("grade");
                        preuserphone = resultObj.getString("preUserPhone");

                        /* 用户证明有上级用户 */
                        if (preuserid != 0 && preuserphone != null && !preuserphone.equalsIgnoreCase("")) {

                            restTemplate = new RestTemplate();
                            uri = util.getServiceUrl("user", "error url request!");
                            url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

                            /* 根据的渠道标识或去渠道的相关信息 */
                            requestEntity = new LinkedMultiValueMap<String, String>();
                            requestEntity.add("channel_id", channelId + "");
                            requestEntity.add("user_id", preuserid + "");

                            result = restTemplate.postForObject(url, requestEntity, String.class);
                            LOG.info("RESULT================" + result);
                            jsonObject = JSONObject.fromObject(result);

                            if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
                                LOG.error("亲.无渠道费率,请配置渠道费率哦!======userId:" + preuserid + "channelId:" + channelId);
//								throw new RuntimeException("亲.无渠道费率,请配置渠道费率哦!");
                                userid = preuserid;
                                continue;
                            }

                            resultObj = jsonObject.getJSONObject("result");
                            rate = resultObj.getString("rate");

                            /* 证明上级的费率小于当前 */
                            if (new BigDecimal(rate).compareTo(currate) < 0) {

                                /* 计算分润的钱 */
                                BigDecimal rebate = (currate.subtract(new BigDecimal(rate))).multiply(amount)
                                        .setScale(2, BigDecimal.ROUND_HALF_UP);
                                if (rebate.toString().equals("0.00")) {
                                    /* 当前用户作为下一次循环的初始用户了 */
                                    userid = preuserid;
                                    currate = new BigDecimal(rate);
                                    break;
                                }
                                /* 存贮分润记录明细 */
                                ProfitRecord profitRecord = new ProfitRecord();
                                profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                                ;
                                profitRecord.setAcqAmount(rebate);
                                profitRecord.setAcqphone(preuserphone);
                                profitRecord.setAcqrate(new BigDecimal(rate));
                                profitRecord.setAcquserid(preuserid);
                                profitRecord.setAmount(amount);
                                profitRecord.setCreateTime(new Date());
                                profitRecord.setOrdercode(ordercode);
                                profitRecord.setOriphone(oriphone);
                                profitRecord.setOrirate(currate);
                                profitRecord.setOriuserid(userid);
                                profitRecord.setRemark("差额费率分润");
                                profitRecord.setScale(BigDecimal.ONE);
                                profitRecord.setType("0");
                                profitRecordBusiness.merge(profitRecord);

                                /* 存储 用户的分润记录 */
                                restTemplate = new RestTemplate();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/rebate/update";
                                /* 根据的渠道标识或去渠道的相关信息 */
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("rebate_amount", rebate.toString());
                                requestEntity.add("user_id", preuserid + "");
                                requestEntity.add("order_code", ordercode);
                                result = restTemplate.postForObject(url, requestEntity, String.class);

                                /* 当前用户作为下一次循环的初始用户了 */
                                userid = preuserid;
                                currate = new BigDecimal(rate);
                                break;
                            }

                        } else {
                            isCancel = true;
                            break;

                        }
                    }

                }

            } else {

                break;
            }
        }


    }
    /* 循环处理用户的分润 */

    /**
     * 分润的发放逻辑如下，如果刷卡用户的上级登记比自己高，那上级那自己的分润，如果上级的等级美欧自己的高，那么继续寻找上面一个比自己低的拿分润
     * 拿到分润的用户作为下一次循环的起点， 直接没有上级为止
     */

    private void rebate(String ordercode, long userid, long channelId, BigDecimal amount, BigDecimal currate,
                        long brandid) {

        boolean isUseEqual = true;

        boolean isCancel = false;
        boolean isequalRebateRate = false;
        String equalRebateRate = "";

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/query/id";

        /* 根据的用户手机号码查询用户的基本信息 */
        requestEntity.add("id", userid + "");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        String grade = resultObj.getString("grade");
        Integer equalGrade = Integer.valueOf("0".equals(grade) ? "1" : grade);
        Integer equalGradeTemp = equalGrade;
        /* 根据userid 找到上级， 如果上级的费率比他低就发放分润，然后继续循环方法 */
        while (true) {

            if (isCancel) {
                break;
            }

            restTemplate = new RestTemplate();
            requestEntity = new LinkedMultiValueMap<String, String>();
            restTemplate = new RestTemplate();
            uri = util.getServiceUrl("user", "error url request!");
            url = uri.toString() + "/v1.0/user/query/id";

            /* 根据的用户手机号码查询用户的基本信息 */
            requestEntity.add("id", userid + "");
            result = restTemplate.postForObject(url, requestEntity, String.class);
            LOG.info("RESULT================" + result);
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
            String oriphone = resultObj.getString("phone");
            long preuserid = resultObj.getLong("preUserId");
            grade = resultObj.getString("grade");

            String preuserphone = resultObj.getString("preUserPhone");

            /* 用户证明有上级用户 */
            if (preuserid != 0 && preuserphone != null && !preuserphone.equalsIgnoreCase("")) {

                restTemplate = new RestTemplate();
                uri = util.getServiceUrl("user", "error url request!");
                url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

                /* 根据的渠道标识或去渠道的相关信息 */
                requestEntity = new LinkedMultiValueMap<String, String>();
                requestEntity.add("channel_id", channelId + "");
                requestEntity.add("user_id", preuserid + "");

                result = restTemplate.postForObject(url, requestEntity, String.class);
                LOG.info("RESULT================" + result);
                jsonObject = JSONObject.fromObject(result);

                if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
                    LOG.error("亲.无渠道费率,请配置渠道费率哦!======userId:" + preuserid + "channelId:" + channelId);
//					throw new RuntimeException("亲.无渠道费率,请配置渠道费率哦!");
                    userid = preuserid;
                    continue;
                }

                resultObj = jsonObject.getJSONObject("result");
                String rate = resultObj.getString("rate");

                /* 证明上级的费率小于当前 */
                if (new BigDecimal(rate).compareTo(currate) < 0) {

                    /* 计算分润的钱 */
                    BigDecimal rebate = (currate.subtract(new BigDecimal(rate))).multiply(amount).setScale(2,
                            BigDecimal.ROUND_HALF_UP);
                    if (rebate.toString().equals("0.00")) {
                        /* 当前用户作为下一次循环的初始用户了 */
                        userid = preuserid;
                        currate = new BigDecimal(rate);
                        continue;
                    }
                    /* 存贮分润记录明细 */
                    ProfitRecord profitRecord = new ProfitRecord();
                    profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                    ;
                    profitRecord.setAcqAmount(rebate);
                    profitRecord.setAcqphone(preuserphone);
                    profitRecord.setAcqrate(new BigDecimal(rate));
                    profitRecord.setAcquserid(preuserid);
                    profitRecord.setAmount(amount);
                    profitRecord.setCreateTime(new Date());
                    profitRecord.setOrdercode(ordercode);
                    profitRecord.setOriphone(oriphone);
                    profitRecord.setOrirate(currate);
                    profitRecord.setOriuserid(userid);
                    profitRecord.setRemark("差额费率分润");
                    profitRecord.setScale(BigDecimal.ONE);
                    profitRecord.setType("0");
                    profitRecordBusiness.merge(profitRecord);

                    /* 存储 用户的分润记录 */
                    restTemplate = new RestTemplate();
                    uri = util.getServiceUrl("user", "error url request!");
                    url = uri.toString() + "/v1.0/user/rebate/update";
                    /* 根据的渠道标识或去渠道的相关信息 */
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("rebate_amount", rebate.toString());
                    requestEntity.add("user_id", preuserid + "");
                    requestEntity.add("order_code", ordercode);
                    result = restTemplate.postForObject(url, requestEntity, String.class);

                    /* 当前用户作为下一次循环的初始用户了 */
                    userid = preuserid;
                    currate = new BigDecimal(rate);
                    continue;

                } else {

                    if (!isequalRebateRate) {
                        /* 根据品牌id获取同级的分润比率 */
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + brandid;
                        result = restTemplate.getForObject(url, String.class);
                        jsonObject = JSONObject.fromObject(result);
                        resultObj = jsonObject.getJSONObject("result");
                        equalRebateRate = resultObj.getString("equalRebateRate");

                        isequalRebateRate = true;
                    }
                    /* 寻找比自己费率低的 */


                    while (true) {

                        /* 先发放同级分润 */
//						if (isUseEqual) {

                        if (equalRebateRate != null && !equalRebateRate.equalsIgnoreCase("")
                                && !equalRebateRate.equalsIgnoreCase("null")) {

                            if (new BigDecimal(equalRebateRate).compareTo(BigDecimal.ZERO) > 0) {

                                restTemplate = new RestTemplate();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/query/id";
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("id", preuserid + "");
                                result = restTemplate.postForObject(url, requestEntity, String.class);
                                LOG.info("RESULT================" + result);
                                jsonObject = JSONObject.fromObject(result);
                                resultObj = jsonObject.getJSONObject("result");
                                String pregrade = resultObj.getString("grade");
                                if (equalGrade.equals(Integer.valueOf(pregrade)) && Integer.parseInt(pregrade) == Integer.parseInt(grade)) {
                                    equalGrade = equalGrade + 1;
                                    isUseEqual = false;
                                    /* 计算分润的钱 */
                                    BigDecimal rebate = new BigDecimal(equalRebateRate).multiply(amount).setScale(2,
                                            BigDecimal.ROUND_HALF_UP);
                                    /* 存贮分润记录明细 */
                                    ProfitRecord profitRecord = new ProfitRecord();
                                    profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                                    profitRecord.setAcqAmount(rebate);
                                    profitRecord.setAcqphone(preuserphone);
                                    profitRecord.setAcqrate(new BigDecimal(rate));
                                    profitRecord.setAcquserid(preuserid);
                                    profitRecord.setAmount(amount);
                                    profitRecord.setCreateTime(new Date());
                                    profitRecord.setOrdercode(ordercode);
                                    profitRecord.setOriphone(oriphone);
                                    profitRecord.setOrirate(currate);
                                    profitRecord.setOriuserid(userid);
                                    profitRecord.setRemark("平级分润");
                                    profitRecord.setScale(BigDecimal.ONE);
                                    profitRecord.setType("3");
                                    profitRecordBusiness.merge(profitRecord);

                                    /* 存储 用户的分润记录 */
                                    restTemplate = new RestTemplate();
                                    uri = util.getServiceUrl("user", "error url request!");
                                    url = uri.toString() + "/v1.0/user/rebate/update";
                                    /* 根据的渠道标识或去渠道的相关信息 */
                                    requestEntity = new LinkedMultiValueMap<String, String>();
                                    requestEntity.add("rebate_amount", rebate.toString());
                                    requestEntity.add("user_id", preuserid + "");
                                    requestEntity.add("order_code", ordercode);
                                    result = restTemplate.postForObject(url, requestEntity, String.class);


                                    LOG.info("平级分润================================受益人:" + preuserid + ",等级:" + pregrade + ",平级等级:" + equalGrade);

                                }
                            } else {

                                isUseEqual = false;

                            }
                        } else {

                            isUseEqual = false;
                        }
//						}

                        restTemplate = new RestTemplate();
                        requestEntity = new LinkedMultiValueMap<String, String>();
                        restTemplate = new RestTemplate();
                        uri = util.getServiceUrl("user", "error url request!");
                        url = uri.toString() + "/v1.0/user/query/id";

                        /* 根据的用户手机号码查询用户的基本信息 */
                        requestEntity.add("id", preuserid + "");
                        result = restTemplate.postForObject(url, requestEntity, String.class);
                        LOG.info("RESULT================" + result);
                        jsonObject = JSONObject.fromObject(result);
                        resultObj = jsonObject.getJSONObject("result");
                        preuserid = resultObj.getLong("preUserId");
                        grade = resultObj.getString("grade");
                        preuserphone = resultObj.getString("preUserPhone");

                        /* 用户证明有上级用户 */
                        if (preuserid != 0 && preuserphone != null && !preuserphone.equalsIgnoreCase("")) {

                            restTemplate = new RestTemplate();
                            uri = util.getServiceUrl("user", "error url request!");
                            url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

                            /* 根据的渠道标识或去渠道的相关信息 */
                            requestEntity = new LinkedMultiValueMap<String, String>();
                            requestEntity.add("channel_id", channelId + "");
                            requestEntity.add("user_id", preuserid + "");

                            result = restTemplate.postForObject(url, requestEntity, String.class);
                            LOG.info("RESULT================" + result);
                            jsonObject = JSONObject.fromObject(result);

                            if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
                                LOG.error("亲.无渠道费率,请配置渠道费率哦!======userId:" + preuserid + "channelId:" + channelId);
//								throw new RuntimeException("亲.无渠道费率,请配置渠道费率哦!");
                                userid = preuserid;
                                continue;
                            }

                            resultObj = jsonObject.getJSONObject("result");
                            rate = resultObj.getString("rate");

                            /* 证明上级的费率小于当前 */
                            if (new BigDecimal(rate).compareTo(currate) < 0) {

                                /* 计算分润的钱 */
                                BigDecimal rebate = (currate.subtract(new BigDecimal(rate))).multiply(amount)
                                        .setScale(2, BigDecimal.ROUND_HALF_UP);
                                if (rebate.toString().equals("0.00")) {
                                    /* 当前用户作为下一次循环的初始用户了 */
                                    userid = preuserid;
                                    currate = new BigDecimal(rate);
                                    break;
                                }
                                /* 存贮分润记录明细 */
                                ProfitRecord profitRecord = new ProfitRecord();
                                profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
                                ;
                                profitRecord.setAcqAmount(rebate);
                                profitRecord.setAcqphone(preuserphone);
                                profitRecord.setAcqrate(new BigDecimal(rate));
                                profitRecord.setAcquserid(preuserid);
                                profitRecord.setAmount(amount);
                                profitRecord.setCreateTime(new Date());
                                profitRecord.setOrdercode(ordercode);
                                profitRecord.setOriphone(oriphone);
                                profitRecord.setOrirate(currate);
                                profitRecord.setOriuserid(userid);
                                profitRecord.setRemark("差额费率分润");
                                profitRecord.setScale(BigDecimal.ONE);
                                profitRecord.setType("0");
                                profitRecordBusiness.merge(profitRecord);

                                /* 存储 用户的分润记录 */
                                restTemplate = new RestTemplate();
                                uri = util.getServiceUrl("user", "error url request!");
                                url = uri.toString() + "/v1.0/user/rebate/update";
                                /* 根据的渠道标识或去渠道的相关信息 */
                                requestEntity = new LinkedMultiValueMap<String, String>();
                                requestEntity.add("rebate_amount", rebate.toString());
                                requestEntity.add("user_id", preuserid + "");
                                requestEntity.add("order_code", ordercode);
                                result = restTemplate.postForObject(url, requestEntity, String.class);

                                /* 当前用户作为下一次循环的初始用户了 */
                                userid = preuserid;
                                currate = new BigDecimal(rate);
                                break;
                            }

                        } else {
                            isCancel = true;
                            break;

                        }
                    }
                    if (equalGradeTemp.equals(equalGrade)) {
                        equalGrade += 1;
                    }
                }
            } else {
                break;
            }
        }

    }

    public int getIntervalDays(Date fDate, Date oDate) {


	 /*if (null == fDate || null == oDate) {

	 return -1;

	 }

	 long intervalMilli = oDate.getTime() - fDate.getTime();

	 return (int) (intervalMilli / (24 * 60 * 60 * 1000));*/


        Calendar aCalendar = Calendar.getInstance();

        aCalendar.setTime(fDate);

        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

        aCalendar.setTime(oDate);
        // aCalendar.add(Calendar.HOUR_OF_DAY, -17);
        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

        return day2 - day1;

    }

    /**
     * 查询提现总金额
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/userid")
    public @ResponseBody
    Object findAllChannelByuserid(
            @RequestParam(value = "user_id") long userid, @RequestParam(value = "type") String type,
            @RequestParam(value = "status", defaultValue = "1", required = false) String status,
            @RequestParam(value = "auto_clearing", defaultValue = "0", required = false) String autoClearing) {
        String[] str1 = type.split(",");
        String[] str2 = status.split(",");
        BigDecimal simrealAmount = paymentOrderBusiness.findsumPaymentOrder(userid, str1, str2, autoClearing);
        Map map = new HashMap();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT,
                simrealAmount == null ? "0.00" : simrealAmount.setScale(2, BigDecimal.ROUND_DOWN));
        return map;
    }

    //	批量查询指定type的总金额
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/byuserids")
    public @ResponseBody
    Object findAllChannelSumByUserIds(
            @RequestParam(value = "userIds") String[] suserIds,
            @RequestParam(value = "type") String type,
            @RequestParam(value = "status", required = false, defaultValue = "1") String status,
            @RequestParam(value = "autoClearing", required = false, defaultValue = "0") String autoClearing
    ) {
        Map<String, Object> map = new HashMap<>();
        Map<Object, Object> sumMap = new HashMap<>();
        long[] userIds = new long[suserIds.length];
        if (suserIds.length > 0) {
            for (int i = 0; i < suserIds.length; i++) {
                userIds[i] = Long.valueOf(suserIds[i]);
            }
            List<Object[]> models = paymentOrderBusiness.findSumByUserIds(userIds, type, status, autoClearing);
            for (Object[] model : models) {
                sumMap.put(model[0], model[1]);
            }
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "查询成功");
            map.put(CommonConstants.RESULT, sumMap);
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询失败");
        }
        return map;
    }

    /**
     * 查询提现总金额
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/sum/userid")
    public @ResponseBody
    Object findAllChannelByuseridsum(
            @RequestParam(value = "user_id") long userid,
            @RequestParam(value = "type", defaultValue = "", required = false) String type,
            @RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
            @RequestParam(value = "end_time", required = false) String startTime,
            @RequestParam(value = "auto_clearing", defaultValue = "0", required = false) String autoClearing) {

        Date startTimeDate;
        if (startTime != null && !startTime.equalsIgnoreCase("")) {
            startTimeDate = DateUtil.getDateFromStr(startTime);
        } else {
            startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            startTimeDate = DateUtil.getDateFromStr(startTime);
        }
        Date endTimeDate = null;
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(startTimeDate);
        calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
        endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
        /* 总入金 **/
        BigDecimal RechargeSum;
        /* 总提现 **/
        BigDecimal withdrawSum;
        /* 交易笔数 **/
        int transactionCount;
        {
            type = "0";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            RechargeSum = paymentOrderBusiness.findsumPaymentOrder(userid, str1, str2, autoClearing, startTimeDate,
                    endTimeDate);
        }
        {
            type = "2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            withdrawSum = paymentOrderBusiness.findsumPaymentOrder(userid, str1, str2, autoClearing, startTimeDate,
                    endTimeDate);
        }
        {
            type = "0,2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            transactionCount = paymentOrderBusiness.findsumPaymentOrderCount(userid, str1, str2, autoClearing,
                    startTimeDate, endTimeDate);
        }

        Map sumall = new HashMap();
        sumall.put("RechargeSum", RechargeSum == null ? "0.00" : RechargeSum.setScale(2, BigDecimal.ROUND_DOWN));
        sumall.put("withdrawSum", withdrawSum == null ? "0.00" : withdrawSum.setScale(2, BigDecimal.ROUND_DOWN));
        sumall.put("transactionCount", transactionCount);
        Map map = new HashMap();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, sumall);
        return map;
    }

    /**
     * 查询提现总金额
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/sum/userid/query")
    public @ResponseBody
    Object findAllChannelByuseridquerysum(HttpServletRequest request,
                                          @RequestParam(value = "user_id") long userid,
                                          @RequestParam(value = "type", defaultValue = "0", required = false) String type,
                                          @RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
                                          @RequestParam(value = "auto_clearing", defaultValue = "0", required = false) String autoClearing) {

        int transactionCount = 0;
        String[] str1 = type.split(",");
        String[] str2 = status.split(",");
        Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
        Date endTimeDate = new Date();
        transactionCount = paymentOrderBusiness.findsumPaymentOrderCount(userid, str1, str2, autoClearing,
                startTimeDate, endTimeDate);

        // Map sumall = new HashMap();
        // sumall.put("transactionCount",transactionCount);
        Map map = new HashMap();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, transactionCount);
        return map;
    }

    /*
     * public static void main(String[] args) throws Exception{
     *
     *
     * String date1 = "2016-07-09 11:23:23"; String date2 =
     * "2016-07-10 17:23:23";
     *
     *
     * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     *
     * Date newDate1 = sdf.parse(date1); Date newDate2 = sdf.parse(date2);
     *
     * Calendar aCalendar = Calendar.getInstance();
     *
     * aCalendar.setTime(newDate1);
     *
     * int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
     *
     * aCalendar.setTime(newDate2); aCalendar.add(Calendar.HOUR_OF_DAY, -17);
     * int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
     *
     * System.out.println(day2 - day1);
     *
     *
     *
     * }
     */

    /**
     * 查询提现brand总金额
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/sum/brand")
    public @ResponseBody
    Object findAllChannelByBrandsum(HttpServletRequest request,
                                    @RequestParam(value = "brand_id") long brandId,
                                    @RequestParam(value = "type", defaultValue = "1", required = false) String type,
                                    @RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
                                    @RequestParam(value = "end_time", required = false) String startTime,
                                    @RequestParam(value = "auto_clearing", defaultValue = "0,1", required = false) String autoClearing) {
        Map daysum = new HashMap();
        Map monthsum = new HashMap();
        Map allsum = new HashMap();
        Map body = new HashMap();
        {
            Date startTimeDate = null;
            if (startTime != null && !startTime.equalsIgnoreCase("")) {
                startTimeDate = DateUtil.getDateFromStr(startTime);
            } else {
                startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                startTimeDate = DateUtil.getDateFromStr(startTime);
            }
            Date endTimeDate = null;
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(startTimeDate);
            calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
            endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
            body.put("daysum", getBrandsum(brandId, startTimeDate, endTimeDate, type, status, autoClearing));
        }
        {
            Date startTimeDate = null;
            if (startTime != null && !startTime.equalsIgnoreCase("")) {
                startTime = new SimpleDateFormat("yyyy-MM").format(DateUtil.getDateFromStr(startTime));
                startTimeDate = getYYMMDateFromStr(startTime);
            } else {
                startTime = new SimpleDateFormat("yyyy-MM").format(new Date());
                startTimeDate = getYYMMDateFromStr(startTime);
            }
            Date endTimeDate = null;
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(startTimeDate);
            calendar.add(calendar.MONTH, 1);// 把日期往后增加一天.整数往后推,负数往前移动
            endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
            body.put("monthsum", getBrandsum(brandId, startTimeDate, endTimeDate, type, status, autoClearing));
        }

        {
            Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
            Date endTimeDate = new Date();
            body.put("allsum", getBrandsum(brandId, startTimeDate, endTimeDate, type, "1", autoClearing));
        }
        Map map = new HashMap();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, body);
        return map;
    }

    /**
     * 获取红包或其他类型今日交易笔数
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/desccode/query/userid")
    public @ResponseBody
    Object findAllChannelByDescCode(HttpServletRequest request,
                                    @RequestParam(value = "user_id") long userid,
                                    @RequestParam(value = "type", defaultValue = "0", required = false) String type,
                                    @RequestParam(value = "status", defaultValue = "1", required = false) String status,
                                    @RequestParam(value = "desc_code", defaultValue = "RedPayment", required = false) String desccode) {
        String[] str1 = type.split(",");
        String[] str2 = status.split(",");
        Date startTimeDate = null;
        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        startTimeDate = DateUtil.getDateFromStr(startTime);
        Date endTimeDate = null;
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(startTimeDate);
        calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
        endTimeDate = calendar.getTime(); //
        List<PaymentOrder> simrealAmount = paymentOrderBusiness.findsumPaymentOrderByDescCode(userid, str1, str2,
                desccode, startTimeDate, endTimeDate);
        Map map = new HashMap();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        if (simrealAmount != null && simrealAmount.size() > 0) {
            map.put(CommonConstants.RESULT, simrealAmount);
        }

        return map;
    }

    /**
     * 查询提现Platform总金额
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/sum/platform")
    public @ResponseBody
    Object findAllChannelByPlatformsum(HttpServletRequest request,
                                       @RequestParam(value = "type", defaultValue = "", required = false) String type,
                                       @RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
                                       @RequestParam(value = "end_time", required = false) String startTime,
                                       @RequestParam(value = "auto_clearing", defaultValue = "0,1", required = false) String autoClearing) {
        Map daysum = new HashMap();
        Map monthsum = new HashMap();
        Map allsum = new HashMap();
        Map body = new HashMap();
        {
            Date startTimeDate = null;
            if (startTime != null && !startTime.equalsIgnoreCase("")) {
                startTimeDate = DateUtil.getDateFromStr(startTime);
            } else {
                startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                startTimeDate = DateUtil.getDateFromStr(startTime);
            }
            Date endTimeDate = null;
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(startTimeDate);
            calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
            endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
            body.put("daysum", getPlatformsum(startTimeDate, endTimeDate, type, status, autoClearing));
        }
        {
            Date startTimeDate = null;
            if (startTime != null && !startTime.equalsIgnoreCase("")) {
                startTime = new SimpleDateFormat("yyyy-MM").format(DateUtil.getDateFromStr(startTime));
                startTimeDate = getYYMMDateFromStr(startTime);
            } else {
                startTime = new SimpleDateFormat("yyyy-MM").format(new Date());
                startTimeDate = getYYMMDateFromStr(startTime);
            }
            Date endTimeDate = null;
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(startTimeDate);
            calendar.add(calendar.MONTH, 1);// 把日期往后增加一天.整数往后推,负数往前移动
            endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果

            body.put("monthsum", getPlatformsum(startTimeDate, endTimeDate, type, status, autoClearing));
        }

        {
            Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
            Date endTimeDate = new Date();
            body.put("allsum", getPlatformsum(startTimeDate, endTimeDate, type, "1", autoClearing));
        }
        Map map = new HashMap();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, body);
        return map;
    }

    // 查询用公众号支付商铺扫码的订单
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/queryPaymentOrder")
    public @ResponseBody
    Object findPaymentOrder(HttpServletRequest request,
                            @RequestParam(value = "brand_id", required = false) Long brandid,
                            @RequestParam(value = "user_id", required = false) Long userId,
                            @RequestParam(value = "order_status", defaultValue = "0,1,2,3,4", required = false) String status,
                            @RequestParam(value = "order_code", defaultValue = "", required = false) String ordercode,
                            @RequestParam(value = "third_order_code", defaultValue = "", required = false) String thirdOrdercode,
                            @RequestParam(value = "channel_tag", defaultValue = "3", required = false) String channel_no,
                            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
                            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
                            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
                            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        //String[] statu = status.split(",");
        //String[] channel = channel_no.split("");

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/channel/channelno";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("channel_no", channel_no);

        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("result========" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String channel = null;
        if (jsonObject.containsKey("result") && jsonObject.getString("result").length() > 0) {
            channel = jsonObject.getString("result");
        }

        PaymentQueryCriteria queryCriteria = new PaymentQueryCriteria();
        queryCriteria.setUser_id(userId);
        queryCriteria.setBrand_id(brandid);
        queryCriteria.setStatus(status);
        queryCriteria.setOrder_code(ordercode);
        queryCriteria.setThird_order_code(thirdOrdercode);
        queryCriteria.setChannel_tag(channel);

        Page<PaymentOrder> pageResult = paymentOrderBusiness.findPaymentOrder(queryCriteria, pageable);
        return CommonsUtil.returnOK(pageResult);
    }

    private Map getPlatformsum(Date startTimeDate, Date endTimeDate, String type, String status, String autoClearing) {
        Map Platformsum = new HashMap();
        /** 总入金 **/
        BigDecimal RechargeSum = null;
        /** 总购买 **/
        BigDecimal buyGoodsSum = null;
        /** 总提现 **/
        BigDecimal withdrawSum = null;
        /** 总交易笔数 **/
        int transactionCount = 0;
        // 提现笔数
        int withdrawCount = 0;
        // 充值笔数
        int rechargeCount = 0;
        // 购买商品笔数
        int buyGoodsCount = 0;

        // 购买商品的金额
        {
            type = "1";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            buyGoodsSum = paymentOrderBusiness.findsumPaymentOrderPlatform(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 充值的金额
        {
            type = "0";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            RechargeSum = paymentOrderBusiness.findsumPaymentOrderPlatform(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 提现的金额
        {
            type = "2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            withdrawSum = paymentOrderBusiness.findsumPaymentOrderPlatform(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 总交易笔数
        {
            type = "0,1,2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            transactionCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 充值的交易笔数
        {
            type = "0";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            rechargeCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 购买商品的交易笔数
        {
            type = "1";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            buyGoodsCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 提现的交易笔数
        {
            type = "2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            withdrawCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 充值的金额
        Platformsum.put("RechargeSum", RechargeSum == null ? "0.00" : RechargeSum.setScale(2, BigDecimal.ROUND_DOWN));
        // 购买商品的金额
        Platformsum.put("buyGoodsSum", buyGoodsSum == null ? "0.00" : buyGoodsSum.setScale(2, BigDecimal.ROUND_DOWN));
        /** 总提现 **/
        Platformsum.put("withdrawSum", withdrawSum == null ? "0.00" : withdrawSum.setScale(2, BigDecimal.ROUND_DOWN));
        /** 总交易笔数 **/
        Platformsum.put("transactionCount", transactionCount);
        Platformsum.put("rechargeCount", rechargeCount);
        Platformsum.put("buyGoodsCount", buyGoodsCount);
        Platformsum.put("withdrawCount", withdrawCount);

        return Platformsum;
    }

    private Map getBrandsum(long brandId, Date startTimeDate, Date endTimeDate, String type, String status,
                            String autoClearing) {
        Map Platformsum = new HashMap();
        /** 总入金 **/
        BigDecimal RechargeSum = null;
        /** 总购买 **/
        BigDecimal buyGoodsSum = null;
        /** 总提现 **/
        BigDecimal withdrawSum = null;
        /** 交易笔数 **/
        int transactionCount = 0;
        // 提现笔数
        int withdrawCount = 0;
        // 充值笔数
        int rechargeCount = 0;
        // 购买商品笔数
        int buyGoodsCount = 0;

        {
            type = "0";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            RechargeSum = paymentOrderBusiness.findsumPaymentOrderBrand(brandId, str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        {
            type = "1";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            buyGoodsSum = paymentOrderBusiness.findsumPaymentOrderBrand(brandId, str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        {
            type = "2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            withdrawSum = paymentOrderBusiness.findsumPaymentOrderBrand(brandId, str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        {
            type = "0,1,2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            transactionCount = paymentOrderBusiness.findsumPaymentOrderBrandCount(brandId, str1, str2, clear,
                    startTimeDate, endTimeDate);
        }
        // 充值的交易笔数
        {
            type = "0";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            rechargeCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 购买商品的交易笔数
        {
            type = "1";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            buyGoodsCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }
        // 提现的交易笔数
        {
            type = "2";
            String[] str1 = type.split(",");
            String[] str2 = status.split(",");
            String[] clear = autoClearing.split(",");
            withdrawCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
                    endTimeDate);
        }

        Platformsum.put("RechargeSum", RechargeSum == null ? "0.00" : RechargeSum.setScale(2, BigDecimal.ROUND_DOWN));
        Platformsum.put("withdrawSum", withdrawSum == null ? "0.00" : withdrawSum.setScale(2, BigDecimal.ROUND_DOWN));
        Platformsum.put("buyGoodsSum", buyGoodsSum == null ? "0.00" : buyGoodsSum.setScale(2, BigDecimal.ROUND_DOWN));
        Platformsum.put("transactionCount", transactionCount);
        Platformsum.put("rechargeCount", rechargeCount);
        Platformsum.put("buyGoodsCount", buyGoodsCount);
        Platformsum.put("withdrawCount", withdrawCount);

        return Platformsum;
    }

    // 盛迪嘉通道——修改订单号
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/updateOrderCode")
    public @ResponseBody
    Object updateOrderCode(HttpServletRequest request,
                           @RequestParam(value = "oldOrderCode") String orderCode,
                           @RequestParam(value = "newOrderCode") String orderNo) {

        String substring = orderNo.substring(0, 10);

        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("order_code", orderCode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================" + result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject resultObj = jsonObject.getJSONObject("result");
        String userid = resultObj.getString("userid");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("paymentchannel", "error url request!");
        url = uri.toString() + "/v1.0/paymentchannel/topup/sdj/querysdjid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("user_id", userid);
        result = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================" + result);
        jsonObject = JSONObject.fromObject(result);
        resultObj = jsonObject.getJSONObject("result");
        String sdjUserId = resultObj.getString("sdjUserId");

        PaymentOrder paymentOrder = null;

        if (substring.equals(sdjUserId)) {
            paymentOrder = paymentOrderBusiness.updatePaymentOrder(orderCode, orderNo);
        }

        Map map = new HashMap();
        if (paymentOrder != null) {
            return CommonsUtil.returnSuccess("修改成功");
        } else {
            return CommonsUtil.returnError("修改失败");
        }

    }

    public static Date getYYMMDateFromStr(String str) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date result = null;
        try {
            result = sdf.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    //获取待结算订单和成功订单
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/queryorderfailed")
    @ResponseBody
    public Object queryOrderFailed(HttpServletRequest request,
                                   @RequestParam(value = "userid") long userid) {
        String[] status = {"0", "1"};
        List<PaymentOrder> orderList = paymentOrderBusiness.findOrderByUseridAndStatus(userid, status);
        return CommonsUtil.returnOK(orderList);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/add/credit/card/manager/order")
    public @ResponseBody
    Object createPaymentOrderToCreditCardManager(HttpServletRequest request,
                                                 @RequestParam(value = "userId") String userIdStr,
                                                 @RequestParam(value = "rate") String rateStr,
                                                 @RequestParam(value = "type") String type,
                                                 @RequestParam(value = "amount") String amountStr,
                                                 @RequestParam(value = "realAmount") String realAmountStr,
                                                 @RequestParam(value = "creditCardNumber") String creditCardNumber,
                                                 @RequestParam(value = "channelTag") String channelTag,
                                                 @RequestParam(value = "orderCode") String orderCode,
                                                 @RequestParam(value = "serviceCharge") String serviceCharge,
                                                 @RequestParam(value = "description", required = false, defaultValue = "") String description,
                                                 @RequestParam(value = "remark", required = false, defaultValue = "") String remark
    ) {
        userIdStr = userIdStr.trim();
        rateStr = rateStr.trim();
        amountStr = amountStr.trim();
        realAmountStr = realAmountStr.trim();
        serviceCharge = serviceCharge.trim();
        orderCode = orderCode.trim();
        type = type.trim();
        channelTag = channelTag.trim();
        Map map = new HashMap();
        long userId = Long.valueOf(userIdStr);
        BigDecimal rate = new BigDecimal(rateStr);

        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("user", "error url request!");
        String url = uri.toString() + "/v1.0/user/find/by/userid";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("userId", userIdStr);
        String resultString;
        JSONObject resultJSONObject;
        try {
            resultString = restTemplate.postForObject(url, requestEntity, String.class);
            resultJSONObject = JSONObject.fromObject(resultString);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "生成订单失败,服务器正忙,请稍后重试!");
            return map;
        }
        LOG.info("RESULT============/v1.0/user/find/by/userid:" + resultString);
        if (!CommonConstants.SUCCESS.equals(resultJSONObject.getString(CommonConstants.RESP_CODE))) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "生成订单失败,无该用户数据!");
            return map;
        }

        resultJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
        long brandId = resultJSONObject.getLong("brandId");
        String phone = resultJSONObject.getString("phone");
        String brandName = resultJSONObject.getString("brandname");

        PaymentOrder paymentOrder = new PaymentOrder();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/channel/query";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("channel_tag", channelTag);
        resultString = restTemplate.postForObject(url, requestEntity, String.class);
        LOG.info("RESULT================/v1.0/user/channel/query:" + resultString);
        resultJSONObject = JSONObject.fromObject(resultString);
        resultJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
        long channelId = resultJSONObject.getLong("id");
        String channelName = resultJSONObject.getString("name");
        String channelTag2 = resultJSONObject.getString("channelTag");
        String channelType = resultJSONObject.getString("channelType");
        String autoClearing = resultJSONObject.getString("autoclearing");
        String costRateStr = resultJSONObject.getString("costRate");
        BigDecimal costRate = new BigDecimal(costRateStr);
        if (!(BigDecimal.ZERO.compareTo(rate) == 0)) {
            if (costRate.compareTo(rate) > 0) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "下单失败,您的费率有异常,请联系管理员!");
                return map;
            }
        }
        paymentOrder.setChannelid(channelId);
        paymentOrder.setChannelname(channelName);
        paymentOrder.setChannelTag(channelTag2);
        paymentOrder.setBankcard(creditCardNumber);
        paymentOrder.setAutoClearing(autoClearing);
        paymentOrder.setRate(rate);
        paymentOrder.setChannelType(channelType);
        paymentOrder.setExtraFee(new BigDecimal(serviceCharge));

        LinkedMultiValueMap<String, String> requestEntity2 = new LinkedMultiValueMap<String, String>();
        requestEntity2.add("channel_id", channelId + "");
        requestEntity2.add("user_id", userId + "");
        Map<String, Object> restTemplateDoPost = restTemplateUtil.restTemplateDoPost("user", "/v1.0/user/channel/rate/query/userid", requestEntity2);
        if (!CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))) {
            return restTemplateDoPost;
        }
        resultJSONObject = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
        LOG.info("==========/v1.0/user/channel/rate/query/userid:" + resultJSONObject);
        String withdrawFee = resultJSONObject.getString("withdrawFee");
        BigDecimal newwithdrawFee = withdrawFee == null || withdrawFee.equalsIgnoreCase("")
                || withdrawFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(withdrawFee);

        paymentOrder.setCostfee(newwithdrawFee);

        paymentOrder.setAmount(new BigDecimal(amountStr));
        paymentOrder.setRealAmount(new BigDecimal(realAmountStr));
        paymentOrder.setUserid(userId);
        paymentOrder.setBrandid(brandId);
        paymentOrder.setBrandname(brandName);
        paymentOrder.setRemark(remark);
        paymentOrder.setCreateTime(new Date());
        paymentOrder.setUpdateTime(new Date());
        paymentOrder.setDesc(description);
        paymentOrder.setOrdercode(orderCode);
        paymentOrder.setPhone(phone);
        paymentOrder.setType(type);
        paymentOrder.setStatus(CommonConstants.ORDER_READY);

        paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        map.put(CommonConstants.RESULT, paymentOrder);
        return map;
    }

    //查询订单添加失败信息
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update/remark")
    public @ResponseBody
    Object addErrorMsg(HttpServletRequest request,
                       @RequestParam(value = "ordercode") String ordercode,
                       @RequestParam(value = "remark") String remark) {
        Map map = new HashMap();
        PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);
        if (paymentOrder == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "订单查询失败");
        } else {
            paymentOrderBusiness.addErrorByOrderCode(ordercode, remark);
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
        }
        return map;
    }

}
